package org.luxor.commons.storage.client.aliyun;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import org.apache.commons.io.IOUtils;
import org.luxor.commons.core.utils.StrKit;
import org.luxor.commons.storage.client.AbstractStorageClient;
import org.luxor.commons.storage.client.AbstractStorageProperties;
import org.luxor.commons.storage.constant.StorageType;
import org.luxor.commons.storage.exception.StorageServiceException;
import org.luxor.commons.storage.exception.StorageTypeNotSupportedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;


/**
 * 阿里云 文件存储服务
 *
 * @author Mr.yan @date 2020/2/8
 */
public class AliyunStorageClient extends AbstractStorageClient {
    private static final Logger logger = LoggerFactory.getLogger(AliyunStorageClient.class);

    /**
     * 阿里云 全局配置项
     */
    private AliyunProperties properties;

    private OSSClient client;

    public AliyunStorageClient(AliyunProperties properties) {
        this.properties = properties;
        if (this.isEnabled()) {
            this.init();
        }
    }

    private void init() {
        logger.info("Initialization Aliyun open ( Running Aliyun Connector)");
        try {
            client = new OSSClient(properties.getEndPoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());
            logger.info("Initialize Aliyun Connector Success,bye");
        } catch (Throwable e) {
            logger.error("Initialize Aliyun Connector Failure!", e);
            throw e;
        }
    }

    @Override
    public AbstractStorageProperties getConfig() {
        return this.properties;
    }

    @Override
    public boolean isEnabled() {
        return properties.isEnabled();
    }

    @Override
    public String upload(byte[] fileByte, String fileName, String suffix) {
        if (!this.isEnabled()) {
            logger.error("[未开启] 阿里云文件存储功能");
            throw new StorageTypeNotSupportedException("[未开启] 阿里云文件存储功能");
        }
        try {
            String fileFullPath = getFilePath(StorageType.ALIYUN, properties.getPrefix(), fileName, suffix);
            logger.info("上传文件,路径:{}", fileFullPath);

            String key = fileFullPath.startsWith(StrKit.SLASH) ? fileFullPath.substring(1) : fileFullPath;
            client.putObject(properties.getBucketName(), key, new ByteArrayInputStream(fileByte));

            return fileFullPath;
        } catch (Exception e) {
            logger.error("上传文件失败，请核对阿里云配置信息", e);
            throw new StorageServiceException("上传文件失败，请核对阿里云配置信息", e);
        }
    }

    @Override
    public byte[] download(String fileFullPath) {
        if (!this.isEnabled()) {
            logger.error("[未开启] 阿里云文件存储功能. fileFullPath:{}", fileFullPath);
            throw new StorageTypeNotSupportedException("[未开启] 阿里云文件存储功能");
        }
        logger.info("下载文件,路径:{}", fileFullPath);

        InputStream is = null;
        try {
            String key = fileFullPath.startsWith(StrKit.SLASH) ? fileFullPath.substring(1) : fileFullPath;
            OSSObject response = client.getObject(properties.getBucketName(), key);
            is = response.getObjectContent();
            return IOUtils.toByteArray(is);
        } catch (Exception e) {
            logger.error("下载文件失败，请核对阿里云配置信息", e);
            throw new StorageServiceException("下载文件失败，请核对阿里云配置信息", e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    @Override
    public void delete(String fileFullPath) {
        if (!this.isEnabled()) {
            logger.error("[未开启] 阿里云文件存储功能. fileFullPath:{}", fileFullPath);
            throw new StorageTypeNotSupportedException("[未开启] 阿里云文件存储功能");
        }
        logger.info("删除文件,路径:{}", fileFullPath);

        try {
            String key = fileFullPath.startsWith(StrKit.SLASH) ? fileFullPath.substring(1) : fileFullPath;
            client.deleteObject(properties.getBucketName(), key);
        } catch (Exception e) {
            logger.error("删除文件失败，请核对阿里云配置信息", e);
            throw new StorageServiceException("删除文件失败，请核对阿里云配置信息", e);
        }
    }

}
